﻿using System;
using System.Collections.Generic;
using System.Text;

namespace WeatherBuiltIn
{
    class CurrentConditionDisplay : IObserver<MeasurementData>
    {
        private IDisposable _unsubscriber;//接口提供一种用于释放非托管资源的机制。

        // 订阅　 
        public virtual void Subscribe(IObservable<MeasurementData> provider)
        {
            if (provider != null)
                _unsubscriber = provider.Subscribe(this);
        }

        //获取数据错误执行的类
        public void OnError(Exception error)
        {
            var original = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("CurrentCondition数据获取错误！");
            Console.ForegroundColor = original;
        }
        //输出类
        public void OnNext(MeasurementData value)

        {
            Console.WriteLine(
                $"Current condition: " +
                $"\n温度：{value.Temperature}C " +
                $"\n湿度：{value.Humidity}% " +
                $"\n压力：{value.Pressure} ");
            Console.WriteLine();
        }
        //输出任务完成后执行取消订阅
        public void OnCompleted()
        {
            Console.WriteLine("CurrentCondition 任务完成");
            Unsubscribe();
        }
        // 取消订阅
        public virtual void Unsubscribe()
        {
            Console.WriteLine("CurrentCondition 取消订阅");
            //Dispose执行与释放或重置非托管资源关联的应用程序定义的任务。
            _unsubscriber.Dispose();
        }
    }
}
